<template>
  <div>
    <section class="content-header">
      <h1>商品编辑<small>Course</small></h1>
      <ol class="breadcrumb">
        <li>
          <router-link to="/"><i class="fa fa-dashboard"></i> 主页</router-link>
        </li>
        <li>
          <router-link to="/shop1/goods"
            ><i class="fa fa-list"></i> 商品列表</router-link
          >
        </li>
        <li class="active">商品编辑</li>
      </ol>
    </section>

    <!-- Main content -->
    <section class="content">
      <Row>
        <Col :md="20" :lg="18">
          <Card class="">
            <Form
              :model="formItem"
              :label-width="120"
              ref="create_good"
              :rules="rule_create_good"
            >
              <FormItem label="商品名称" prop="name">
                <Input v-model="formItem.name" placeholder="请输入商品名称" />
              </FormItem>

              <FormItem label="图片介绍" prop="image">
                <ImageUpload
                  style="margin-left: 10px"
                  @on-confirm="confirm_images"
                >
                  <Button type="primary">上传图片</Button>
                </ImageUpload>
                <div class="textshow">请上传比例为1:1的图片</div>
                <div class="formItemImage">
                  <div
                    v-for="(item, index) in img"
                    :key="index"
                    :style="`background-image:url('${item}');
                          background-repeat: no-repeat;
                          position: relative;
                          background-position:center center;
                          background-size: cover;
                          width:165px;height:105px;
                          margin-left:10px;
                          margin-bottom:10px;
                          cursor:zoom-in;`"
                  >
                    <i
                      style="
                        position: absolute;
                        right: -8px;
                        top: -8px;
                        color: rgb(255, 0, 0);
                        font-size: 26px;
                        cursor: pointer;
                      "
                      @click.stop="deleteimg(index)"
                      title="删除"
                      class="anliIcon2 ivu-icon ivu-icon-ios-close-circle"
                    ></i>
                  </div>
                </div>
              </FormItem>
              <FormItem label="商品分类" prop="price">
                <Select
                  v-model="formItem.typeId"
                  @on-change="change_type"
                  style="width: 200px"
                  placeholder="请选择商品分类"
                >
                  <Option
                    v-for="(item, index) in count_scale"
                    :value="item.id"
                    :key="index"
                    >{{ item.type }}</Option
                  >
                </Select>
              </FormItem>
              <FormItem label="商品售价" prop="price">
                <Input
                  v-model="formItem.price"
                  type="number"
                  placeholder="实际价格"
                />
              </FormItem>
              <FormItem label="库存" prop="inventory">
                <Input
                  v-model="formItem.inventory"
                  type="number"
                  placeholder="商品库存"
                />
              </FormItem>
              <FormItem label="售卖时间" prop="sellTime">
                <DatePicker
                  type="date"
                  confirm
                  :value="formItem.sellTime"
                  @on-change="formItem.sellTime = $event"
                  placeholder="售卖时间"
                  format="yyyy-MM-dd"
                ></DatePicker>
              </FormItem>
              <FormItem label="是否为直卖商品" prop="kind">
                <i-switch
                  v-model="formItem.kind"
                  :true-value="1"
                  :false-value="0"
                ></i-switch>
              </FormItem>
              <FormItem label="排序">
                <Input
                  v-model="formItem.sort"
                  type="number"
                  placeholder="排序值 值越小排序越靠前"
                />
              </FormItem>

              <Divider dashed></Divider>
              <FormItem label="使用规格" prop="employ">
                <i-switch
                  v-model="formItem.employ"
                  :true-value="1"
                  :false-value="0"
                ></i-switch>
              </FormItem>

              <FormItem label="标签" v-if="formItem.employ">
                <div
                  v-for="(group_item, group_index) in spec_group"
                  :key="group_index"
                >
                  <Tag
                    v-for="(value_item, value_index) in group_item.value"
                    :key="value_index"
                    :name="group_index + ':' + value_index"
                    closable
                    @on-close="delete_spec_value"
                    type="border"
                    :data-gropidx="group_index"
                    >{{ value_item }}</Tag
                  >
                  <!-- 添加规格值 -->
                  <div>
                    <Input
                      v-model="spec_value_ipt[group_index]"
                      style="width: 200px"
                    />
                    <Button @click="add_spec_value(group_index)" shape="circle"
                      >添加规格值</Button
                    >
                  </div>
                </div>
                <Button @click="generate_spec">生成规格列表 </Button>
                注意：删除规格组或规格值后应重新生成规格列表！
              </FormItem>
              <div v-if="formItem.employ">
                <Table
                  border
                  :columns="skuColumns"
                  :data="skuListData"
                  v-if="skuListData.length > 0"
                  style="margin: 10px 0"
                >
                  <template slot-scope="{ index }" slot="stock">
                    <Input
                      v-model="skuListData[index].stock"
                      style="width: 100%"
                      :rules="{
                        required: true,
                        message: '库存必填',
                        trigger: 'blur',
                      }"
                    />
                  </template>
                  <template slot-scope="{ index }" slot="skuprice">
                    <Input
                      v-model="skuListData[index].price"
                      style="width: 100%"
                      :rules="{
                        required: true,
                        message: '价格必填',
                        trigger: 'blur',
                      }"
                    />
                  </template>
                  <template slot-scope="{ index }" slot="action">
                    <Button
                      type="error"
                      size="small"
                      @click="remove_spec_item(index)"
                      >删除</Button
                    >
                  </template>
                </Table>
              </div>
              <Divider dashed></Divider>
              <FormItem label="商品详情" prop="detail">
                <!-- <Input v-model="formItem.intro" type="textarea" :autosize="{minRows:3,maxRows: 5}" placeholder="请输入课程简介"></Input> -->
                <kindeditor
                  id="editor_id"
                  height="500px"
                  width="100%"
                  :content="formItem.introduce"
                  v-model="formItem.introduce"
                ></kindeditor>
              </FormItem>
              <FormItem>
                <Button
                  size="large"
                  type="primary"
                  @click="submit"
                  :loading="loading"
                  ><span class="button_large">提交</span></Button
                >
                <Button size="large" style="margin-left: 8px" @click="cancel"
                  ><span class="button_large">取消</span></Button
                >
              </FormItem>
            </Form>
          </Card>
        </Col>
      </Row>
    </section>
  </div>
</template>

<script>
import courseapi from "@/api/shop1";
import kindeditor from "@/components/kindeditor.vue";
import ImageUpload from "@/components/ImagePanel.vue";
export default {
  components: {
    kindeditor,
    ImageUpload,
  },
  data() {
    const validateprice = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入商品售价"));
      } else {
        callback();
      }
    };
    const validateinventory = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入库存量"));
      } else {
        callback();
      }
    };
    return {
      hospitalImage: "",
      img: [],
      loading: false,
      update: false,
      id: "",

      category: [],
      category2: [],
      category3: [],
      category1_idx: "",
      category2_idx: "",
      category3_idx: "",

      openmarket: false,
      market: "",
      end_time: "",

      formItem: {
        typeId: "",
        name: "",
        sellTime: "",
        img: "",
        introduce: "",
        price: "",
        sort: "",
        inventory: "",
        state: 1,
        employ: 0,
        commodity:0,
        kind: 1,
        specification: [],
        jsonObject: [],
      },
      count_scale: [],

      teachers: [],

      rule_create_good: {
        name: [
          {
            required: true,
            message: "名称不能为空",
            trigger: "blur",
          },
        ],
        price: [
          {
            validator: validateprice,
            message: "请输入商品售价",
            trigger: "blur",
          },
        ],
        inventory: [
          {
            validator: validateinventory,
            message: "请输入库存量",
            trigger: "blur",
          },
        ],
      },
      spec_group: [
        {
          name: "标签",
          value: [],
        },
      ], 
      skuListData: [], 
      spec_group_ipt: "",
      spec_value_ipt: [],

      skuColumns: [
        {
          title: "标签",
          key: "name",
          align: "center",
        },
        {
          title: "库存",
          slot: "stock",
        },
        {
          title: "价格",
          slot: "skuprice",
        },
        {
          title: "操作",
          slot: "action",
          width: 80,
          align: "center",
        },
      ],
    };
  },
  watch: {
    hospitalImage(val) {
      this.img.push(val);
    },
  },
  created() {
    this.lookrecord();
    if (typeof this.$route.query.id != "undefined") {
      this.update = true;
      let id = this.$route.query.id;
      this.id = id;
      courseapi
        .getSingleGoods({
          id: id,
        })
        .then((response) => {
          console.log(response);
          if (response.data.code == 0) {
            let resdata = response.data.data.allSpecification;
            this.formItem = response.data.data;
            console.log(this.formItem);
            this.img = (this.formItem.img || "").split(",");
            if (this.formItem.employ == 1) {
              this.spec_group = JSON.parse(this.formItem.specification); 

              console.log(resdata);
              this.skuListData = resdata;
              delete this.formItem.allSpecification;
              this.$forceUpdate();
            }
          }
        });
    }
  },
  methods: {
    lookrecord() {
      var _this = this;
      courseapi
        .gettypelist({
          page: 1,
          pageSize: 100000,
        })
        .then((response) => {
          console.log(response);
          if (response.data.code == 0) {
            _this.count_scale = response.data.data.list;
            this.loading = false;
          } else {
            this.$Message.error("请求失败!");
          }
        })
        .catch((error) => {
          console.log(error);
          this.loading = false;
          this.$Message.error("请求失败!");
        });
    },
    change_type(val) {
      console.log(val);
      this.formItem.cb_type = "";
      this.formItem.cb_type = val;
    },
    deleteimg(index) {
      this.img.splice(index, 1);
    },
    confirm_images(val) {
      this.img.push(...val);
    },
    add_spec_group() {
      this.spec_group_ipt = "";
      let skuColumns = this.skuColumns;
      skuColumns.splice(skuColumns.length - 3, 0, {
        key: "标签",
        title: "标签",
        width: 150,
      });
    },
    delete_spec_group(event, index) {
      console.log(index);
      let name = this.spec_group[index].name;
      this.spec_group.splice(index, 1);
      let _skuColumns = JSON.parse(JSON.stringify(this.skuColumns));
      console.log("_skucolumns", _skuColumns);
      _skuColumns.forEach((skuItem, _index) => {
        if (skuItem.title === name) {
          this.skuColumns.splice(_index, 1);
          console.log("this.skuColumns", this.skuColumns);
        }
      });
    },
    add_spec_value(group_index) {
      let values = this.spec_group[group_index].value;
      let input_val = this.spec_value_ipt[group_index];
      if (input_val == "") {
        console.log("空");
        return;
      }
      for (let index = 0; index < values.length; index++) {
        if (values[index] == input_val) {
          console.log("已添加");
          return;
        }
      }
      values.push(input_val);
      this.spec_group[group_index].value = values;
      this.spec_value_ipt[group_index] = "";
      this.$forceUpdate();
    },
    delete_spec_value(event, data) {
      let strs = data.split(":");
      let group_index = strs[0];
      let value_index = strs[1];
      this.spec_group[group_index].value.splice(value_index, 1);
    },
    generate_spec() {
      console.log(this.spec_group)
      const confirm = () => {
        return new Promise((resolve, reject) => {
          this.$Modal.confirm({
            title: "提示",
            content:
              "确认要重新生成规格项吗？<br>操作将实时删除原有规格项且不可逆转！",
            onOk: () => {
              resolve(true);
            },
            onCancel: () => {
              reject(false);
            },
          });
        });
      };
      confirm()
        .then(() => {
          let spec_group = this.spec_group;
          let skuList = [];

          let skuValues = [];
          let columns = [];

          spec_group.forEach((item) => {
            skuValues.push(item.value);
            columns.push(item.name);
          });
          skuList = descartes(skuValues, columns);
          console.log(skuList);
          let skuListData = [];
          skuList.forEach((sku_item) => {
            let itm = {};
            let properties = "";
            let name = "";
            for (let idx = 0; idx < columns.length; idx++) {
              let value =
                typeof sku_item == "string" ? sku_item : sku_item[idx];
              itm[columns[idx]] = value;
              properties += columns[idx] + ":" + value + ";";
              name += value + " ";
            }
            itm.properties = properties.substring(0, properties.length - 1);
            itm.name = name.substring(0, name.length - 1);
            skuListData.push(itm);
          });

          this.skuListData = skuListData;
          function descartes(_array) {
            if (_array.length < 2) return _array[0] || [];
            return [].reduce.call(_array, function (col, set) {
              var res = [];
              col.forEach(function (c) {
                set.forEach(function (s) {
                  var t = [].concat(Array.isArray(c) ? c : [c]);
                  t.push(s);
                  res.push(t);
                });
              });
              return res;
            });
          }
        })
        .then(() => {
          if (this.update) {
            console.log("更新商品id", this.id);
            courseapi
              .deleteGuige({
                id: this.id,
              })
              .then((response) => {
                console.log(response);
                if (response.data.code == 0) {
                  this.$Message.success("原规格项删除成功！");
                } else {
                  this.$Message.error("原规格项删除失败");
                }
              });
          }
        });
    },
    remove_spec_item(index) {
      console.log(this.skuListData)
      this.$Modal.confirm({
        title: "提示",
        content: "确认要删除此规格项吗？<br>删除后无法恢复",
        onOk: () => {
          if (this.skuListData[index].id != undefined) {
            courseapi
              .deleteGuigesignle({
                id: this.skuListData[index].id,
              })
              .then((response) => {
                console.log(this.skuListData);
                console.log({ id: this.skuListData[index].id });
                console.log(response);
                if (response.data.code == 0) {
                  this.$Message.success("删除成功！");
                } else {
                  this.$Message.error("保存失败");
                }
              });
          }
          this.skuListData.splice(index, 1);
        },
        onCancel: () => {},
      });
    },
    cancel() {
      this.$router.go(-1);
    },
    submit() {
      this.loading = true;
      console.log(this.formItem);
      let formData = JSON.parse(JSON.stringify(this.formItem));
      if (formData.total == "") {
        this.$Message.error("请填写库存");
        this.loading = false;
        return;
      }
      if (formData.employ == 1) {
        let specification = JSON.parse(JSON.stringify(this.spec_group));
        formData.specification = JSON.stringify(specification);
        let jsonObject = JSON.parse(JSON.stringify(this.skuListData));
        jsonObject.forEach((item) => {
          specification.forEach((header) => {
            delete item[header.name];
          });
        });
        console.log("规格");
        console.log(jsonObject);
        formData.jsonObject = JSON.stringify(jsonObject);
      } else {
        (formData.jsonObject = ""), (formData.specification = "");
      }
      formData.img = (this.img || "").join(",");
      console.log(formData);
      if (formData.inventory) {
        formData.inventory = Number(formData.inventory);
      } else {
        formData.inventory = 999;
      }

      formData.price = Number(formData.price);
      formData.sort = Number(formData.sort);
      formData.price = Number(formData.price);
      this.$refs["create_good"].validate((valid) => {
        if (valid) {
          console.log(formData);
          if (this.update) {
            formData.id = this.id;
            courseapi
              .updateGoods(formData)
              .then((response) => {
                console.log(formData);
                console.log(response);
                if (response.data.code == 0) {
                  this.$Message.success("保存成功！");
                  this.$router.go(-1);
                } else {
                  this.loading = false;
                  this.$Message.error("保存失败");
                }
              })
              .catch((error) => {
                console.log(error);
                this.loading = false;
                this.$Message.error("保存失败!");
              });
          } else {
            courseapi
              .addGoods(formData)
              .then((response) => {
                console.log(response);
                if (response.data.code == 0) {
                  this.$Message.success("添加成功");
                  this.$router.go(-1);
                } else {
                  this.loading = false;
                  this.$Message.error("添加失败");
                }
              })
              .catch((error) => {
                console.log(error);
                this.loading = false;
                this.$Message.error("添加失败!");
              });
          }
        } else {
          this.loading = false;
          this.$Message.error("请填写必填项!");
        }
      });
    },
  },
};
</script>

<style scoped>
.textshow {
  font-size: 12px;
  color: #333;
  padding-left: 9px;
}
.image {
  max-width: 400px;
  max-height: 200px;
  margin: 10px;
}
.formItemImage {
  display: flex;
  justify-items: left;
  align-items: center;
  flex-wrap: wrap;
}
.formItemImage .ivu-col {
  margin-bottom: 16px;
}
.formItemImage img {
  height: 100%;
}
.button_large {
  padding: 0px 20px;
}
.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>